﻿@inject IThemeService themeService
@inject IUserConfigService configService
@inject ILogger<ThemeSwitcher> logger
@inject IJSRuntime JsRuntime
@implements IDisposable

@if( themeSet )
{
    <div class="themeswitcher-fade">
        <MudThemeProvider Theme="@mudTheme"/>
        @ChildContent
    </div>
}

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }

    private long cacheBuster = 1;
    private MudTheme? mudTheme;
    private ThemeConfig? currentConfig;
    private bool themeSet = false;

    protected override void OnInitialized()
    {
        themeService.OnChangeTheme += ThemeChanged;
        base.OnInitialized();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if( firstRender )
        {
            if( mudTheme == null )
            {
                var themeName = configService.Get(ConfigSettings.Theme, "Green");

                if( !string.IsNullOrEmpty(themeName) )
                {
                    currentConfig = await themeService.GetThemeConfig(themeName);
                    await SwitchTheme(currentConfig);
                }
            }
        }
    }

    public void Dispose()
    {
        themeService.OnChangeTheme -= ThemeChanged;
    }

    private static MudColor CreateMudColor(string value)
    {
        return new MudColor(value);
    }

    public MudTheme CreateMudTheme(ThemeConfig theme)
    {
        return new MudTheme
        {
            PaletteLight = new PaletteLight()
            {
                Black = CreateMudColor(theme.Black),
                Primary = CreateMudColor(theme.Primary),
                Surface = CreateMudColor(theme.Surface),
                TextPrimary = CreateMudColor(theme.TextPrimary),
                TextSecondary = CreateMudColor(theme.TextSecondary),
                ActionDefault = CreateMudColor(theme.ActionDefault),
                TableLines = CreateMudColor(theme.TableLines),
                LinesInputs = CreateMudColor(theme.LinesInputs),
                TextDisabled = CreateMudColor(theme.TextDisabled),
                Tertiary = CreateMudColor(theme.Tertiary),
                ActionDisabledBackground = CreateMudColor(theme.ActionDisabledBackground),
                ActionDisabled = CreateMudColor(theme.ActionDisabled),
                Background = CreateMudColor(theme.Background),
                BackgroundGray = CreateMudColor(theme.BackgroundGrey),
                DrawerBackground = CreateMudColor(theme.DrawerBackground),
                DrawerText = CreateMudColor(theme.DrawerText),
                DrawerIcon = CreateMudColor(theme.DrawerIcon),
                AppbarBackground = CreateMudColor(theme.AppbarBackground),
                AppbarText = CreateMudColor(theme.AppbarText),
                Divider = CreateMudColor(theme.Divider),
                DividerLight = CreateMudColor(theme.DividerLight),
                LinesDefault = CreateMudColor(theme.LinesDefault)
            }
        };
    }

    private void ThemeChanged( ThemeConfig newTheme )
    {
        _ = SwitchTheme(newTheme);
    }

    private async Task SwitchTheme(ThemeConfig? newTheme)
    {
        if( newTheme != null )
        {
            // Apply the new stylesheet to Damselfly
            var themeCSS = $"{newTheme.Path}?j={cacheBuster++}";
            await JsRuntime.InvokeAsync<string>("setStyleSheet", themeCSS);

            mudTheme = CreateMudTheme(newTheme);
            themeSet = true;
            StateHasChanged();

            logger.LogInformation($"Switched theme to {newTheme}");
        }
    }

}